package com.shinektv.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.LinkProperties;
import android.net.NetworkInfo;
import android.net.RouteInfo;
import android.os.Build;
import android.os.storage.StorageManager;
import android.telephony.TelephonyManager;
import android.text.InputType;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

public class SystemUtil {

    /**
     * 无线网络
     */
    public static final String NETWORK_TYPE_WIFI = "WIFI";
    /**
     * 蓝牙
     */
    public static final String NETWORK_TYPE_BLUETOOTH = "Bluetooth";
    /**
     * 有线网络
     */
    public static final String NETWORK_TYPE_ETHERNET = "Ethernet";
    /**
     * 移动网络2G
     */
    public static final String NETWORK_TYPE_2G = "2G";
    /**
     * 移动网络3G
     */
    public static final String NETWORK_TYPE_3G = "3G";
    /**
     * 移动网络4G
     */
    public static final String NETWORK_TYPE_4G = "4G";


    public static final String IP_SETUP_DHCP = "dhcp";
    public static final String IP_SETUP_MANUAL = "manual";

    private static String OTA_VERSION = "";

    /**
     * 获取当前应用的进程名
     */
    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return "";
    }

    /**
     * 获取view在当前窗口内的绝对坐标
     */
    public static int[] getViewLocationInWindow(View view) {
        int[] location = new int[]{0, 0};
        if (view != null) {
            view.getLocationInWindow(location);
        }
        return location;
    }

    /**
     * 获取view在整个屏幕内的绝对坐标
     */
    public static int[] getViewLocationOnScreen(View view) {
        int[] location = new int[]{0, 0};
        if (view != null) {
            view.getLocationOnScreen(location);
        }
        return location;
    }

    /**
     * 获取系统MAC号
     */
    public static String getMac() {
        String mac = "";
        mac = getPerMac("/sys/class/net/eth0/address");
        if (mac.equals("")) {
            mac = getPerMac("/sys/class/net/wlan0/address");
        }
        if (mac.equals("")) {
            mac = getMacAddressFromIp().replace(":", "");
        }
        return mac;
    }

    /**
     * 获取系统MAC号
     */
    public static String gethMacSymbol() {
        String mac = "";
        mac = getPerMac("/sys/class/net/eth0/address");
        if (mac.equals("")) {
            mac = getPerMac("/sys/class/net/wlan0/address");
        }
        if (mac.equals("")) {
            mac = getMacAddressFromIp();
        }
        return mac;
    }

    public static void enableEthe(Context context, String ip_setup_type,
                                  String addr, String gw, String dns) {
        Intent intent = new Intent("action.ktv.net.receiver");
        intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        if (ip_setup_type.equals(IP_SETUP_DHCP)) {
            intent.putExtra("ip_setup_key", IP_SETUP_DHCP);
            intent.putExtra("ip_addr_static", "1"); //云猫 设置静态IP   0静态ip  1取消静态ip
        } else if (ip_setup_type.equals(IP_SETUP_MANUAL)) {
            intent.putExtra("ip_setup_key", IP_SETUP_MANUAL);
            intent.putExtra("ip_addr_static", "0"); //云猫 设置静态IP   0静态ip  1取消静态ip
            intent.putExtra("ip_addr_key", addr);
            intent.putExtra("ip_gateway_key", gw);
            intent.putExtra("ip_mask_key", "24");
            intent.putExtra("ip_dns_key", dns);
            intent.putExtra("ip_dns2_key", "114.114.114.114");
        } else {
            throw new RuntimeException("unsupport ip setup tyep:" + ip_setup_type);
        }
        context.sendBroadcast(intent);

    }

    public static void enableEthe(Context context, String ip_setup_type,
                                  String addr, String gw, String mask, String dns) {
        if ("255.255.255.0".equals(mask)) {
            mask = "24";
        } else if ("255.255.0.0".equals(mask)) {
            mask = "16";
        } else if ("255.0.0.0".equals(mask)) {
            mask = "8";
        }
        Intent intent = new Intent("action.ktv.net.receiver");
        intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        if (ip_setup_type.equals(IP_SETUP_DHCP)) {
            intent.putExtra("ip_setup_key", "dhcp");
            intent.putExtra("ip_addr_static", "1"); //云猫 设置静态IP   0静态ip  1取消静态ip
        } else if (ip_setup_type.equals(IP_SETUP_MANUAL)) {
            intent.putExtra("ip_setup_key", IP_SETUP_MANUAL);
            intent.putExtra("ip_addr_static", "0"); //云猫 设置静态IP   0静态ip  1取消静态ip
            intent.putExtra("ip_addr_key", addr);
            intent.putExtra("ip_gateway_key", gw);
            intent.putExtra("ip_mask_key", mask);
            intent.putExtra("ip_dns_key", dns);
            intent.putExtra("ip_dns2_key", "114.114.114.114");
        } else {
            throw new RuntimeException("unsupport ip setup tyep:" + ip_setup_type);
        }
        context.sendBroadcast(intent);
    }

    public static String getPerMac(String path) {
        String mac = "";
        File file = new File(path);
        if (!file.exists()) return mac;

        Reader reader = null;
        FileInputStream in = null;
        try {
            // 一次读一个字符
            reader = new InputStreamReader(in = new FileInputStream(file));
            int tempchar;
            while ((tempchar = reader.read()) != -1) {
                // 对于windows下，\r\n这两个字符在一起时，表示一个换行。
                // 但如果这两个字符分开显示时，会换两次行。
                // 因此，屏蔽掉\r，或者屏蔽\n。否则，将会多出很多空行。
                if (((char) tempchar) != '\r' && ((char) tempchar) != '\n' && ((char) tempchar) != ':') {
                    mac += (char) (tempchar);
                }
            }

        } catch (Exception e) {
//            e.printStackTrace();
        } finally {
            if (null != reader)
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (null != in)
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            return mac;
        }
    }

    public static String getCPUSerial() {
        String myCpuSerial = "";
        String chipSerial = null;
        FileReader fr = null;
        BufferedReader br = null;
        try {
            fr = new FileReader("/proc/cpuinfo");
            br = new BufferedReader(fr);
            String readline = null;
            while ((readline = br.readLine()) != null) {
                if (readline.trim().toLowerCase().startsWith("serial")) {
                    chipSerial = readline;
                    break;
                }
            }
        } catch (IOException io) {
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                }
            }
        }

        String[] serialSplit = chipSerial != null ? chipSerial.split(":") : null;
        if (serialSplit != null && serialSplit.length == 2) {
            myCpuSerial = serialSplit[1].trim();
        }
        return myCpuSerial;
    }


    public static String getMacAddressFromIp() {
        String mac_s = "";
        StringBuilder buf = new StringBuilder();
        try {
            byte[] mac;
//            WifiManager mWifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
            NetworkInterface ne = NetworkInterface.getByInetAddress(InetAddress.getByName(getActiveIpAddress()));
//            NetworkInterface ne=NetworkInterface.getByInetAddress(InetAddress.getByName(mWifiManager.getConnectionInfo().getIpAddress()));
            mac = ne.getHardwareAddress();
            for (byte b : mac) {
                buf.append(String.format("%02X:", b));
            }
            if (buf.length() > 0) {
                buf.deleteCharAt(buf.length() - 1);
            }
            mac_s = buf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return mac_s;
    }

    /**
     * 检查网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context
                .getApplicationContext().getSystemService(
                        Context.CONNECTIVITY_SERVICE);

        if (manager == null) {
            return false;
        }

        @SuppressLint("MissingPermission")
        NetworkInfo networkinfo = manager.getActiveNetworkInfo();

        if (networkinfo == null || !networkinfo.isAvailable()) {
            return false;
        }

        return true;
    }

    /**
     * 判断WIFI网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean isWifiConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            @SuppressLint("MissingPermission")
            NetworkInfo mWiFiNetworkInfo = mConnectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (mWiFiNetworkInfo != null) {
                return mWiFiNetworkInfo.isAvailable();
            }
        }
        return false;
    }


    /**
     * 判断MOBILE网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean isMobileConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            @SuppressLint("MissingPermission")
            NetworkInfo mMobileNetworkInfo = mConnectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (mMobileNetworkInfo != null) {
                return mMobileNetworkInfo.isAvailable();
            }
        }
        return false;
    }


    /**
     * 获取当前网络连接的类型信息
     *
     * @param context
     * @return
     */
    public static int getConnectedType(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            @SuppressLint("MissingPermission")
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
                return mNetworkInfo.getType();
            }
        }
        return -1;
    }

    /**
     * 获取当前活动IP
     *
     * @return
     */
    public static String getActiveIpAddress() {
        String[] ips = getLocalIpAddress();
        if (ips[0] != null) {
            return ips[0];
        } else if (ips[1] != null) {
            return ips[1];
        }
        return "";
    }

    /**
     * 获取wifi IP
     *
     * @return
     */
    public static String getWifiIpAddress() {
        String[] ips = getLocalIpAddress();
        if (ips[1] != null) {
            return ips[1];
        }

        return "0.0.0.0";
    }

    /**
     * 获取有线IP
     *
     * @return
     */
    public static String getEtheIpAddress() {
        String[] ips = getLocalIpAddress();
        if (ips[0] != null) {
            return ips[0];
        }
        return "0.0.0.0";
    }

    //获取IP
    private static String[] getLocalIpAddress() {
        String[] ret = new String[2];
        try {
            List<NetworkInterface> nilist = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface ni : nilist) {
                List<InetAddress> ialist = Collections.list(ni.getInetAddresses());
                for (InetAddress address : ialist) {
                    if (!address.isLoopbackAddress() && InfoVerify.ipV4Check(address.getHostAddress())) {
                        if (ni.getName().startsWith("wlan")) {
                            ret[1] = address.getHostAddress();
                            Log.d("getLocalIpAddress", "ret[WIFI] is " + ret[1]);
                        } else {
                            ret[0] = address.getHostAddress();
                            Log.d("getLocalIpAddress", "ret[NET] is " + ret[0]);
                        }
                    }
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        return ret;
    }

    static Object invokeMethod(Object object, String methodName, Class<?>[] paramTypes, Object[] values) {
        try {
            Method method = object.getClass().getDeclaredMethod(methodName, paramTypes);
            method.setAccessible(true);
            return method.invoke(object, values);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getEtheMode(Context mContext) {
        if (mContext == null) return "";
        String ETHERNET_SERVICE = null;
        try {
            ETHERNET_SERVICE = (String) Context.class.getField("ETHERNET_SERVICE").get(null);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Class<?> ethernetManagerClass = null;
        try {
            ethernetManagerClass = Class.forName("android.net.EthernetManager");
        } catch (Exception e) {
            e.printStackTrace();
        }

        Class<?> ipConfigurationClass = null;
        try {
            ipConfigurationClass = Class.forName("android.net.IpConfiguration");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        //获取ethernetManager服务对象
        Object ethernetManager = mContext.getSystemService(ETHERNET_SERVICE);

        Object getConfiguration = null;
        Object mode = null;
        try {
            int androidVersion = Build.VERSION.SDK_INT;
            //android 9
            if (androidVersion >= 28) {
                getConfiguration = ethernetManagerClass.getDeclaredMethod("getConfiguration", new Class[]{String.class}).invoke(ethernetManager, new Object[]{"eth0"});
            } else {
                getConfiguration = ethernetManagerClass.getDeclaredMethod("getConfiguration").invoke(ethernetManager);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            mode = ipConfigurationClass.getDeclaredMethod("getIpAssignment").invoke(getConfiguration);
            return mode.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String GetNetworkType(Context context) {
        String strNetworkType = "";
        ConnectivityManager connMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        @SuppressLint("MissingPermission")
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnected()) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                strNetworkType = NETWORK_TYPE_WIFI;//无线
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_BLUETOOTH) {
                strNetworkType = NETWORK_TYPE_BLUETOOTH;//蓝牙
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
                strNetworkType = NETWORK_TYPE_ETHERNET;//以太网
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                String _strSubTypeName = networkInfo.getSubtypeName();
                // TD-SCDMA   networkType is 17
                int networkType = networkInfo.getSubtype();
                switch (networkType) {
                    case TelephonyManager.NETWORK_TYPE_GPRS:
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                    case TelephonyManager.NETWORK_TYPE_1xRTT:
                    case TelephonyManager.NETWORK_TYPE_IDEN: //api<8 : replace by 11
                        strNetworkType = NETWORK_TYPE_2G;
                        break;
                    case TelephonyManager.NETWORK_TYPE_UMTS:
                    case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    case TelephonyManager.NETWORK_TYPE_HSDPA:
                    case TelephonyManager.NETWORK_TYPE_HSUPA:
                    case TelephonyManager.NETWORK_TYPE_HSPA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_B: //api<9 : replace by 14
                    case TelephonyManager.NETWORK_TYPE_EHRPD:  //api<11 : replace by 12
                    case TelephonyManager.NETWORK_TYPE_HSPAP:  //api<13 : replace by 15
                        strNetworkType = NETWORK_TYPE_3G;
                        break;
                    case TelephonyManager.NETWORK_TYPE_LTE:    //api<11 : replace by 13
                        strNetworkType = NETWORK_TYPE_4G;
                        break;
                    default:
                        // http://baike.baidu.com/item/TD-SCDMA 中国移动 联通 电信 三种3G制式
                        if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA") || _strSubTypeName.equalsIgnoreCase("WCDMA") || _strSubTypeName.equalsIgnoreCase("CDMA2000")) {
                            strNetworkType = "3G";
                        } else {
                            strNetworkType = _strSubTypeName;
                        }
                        break;
                }
            }
        }
        return strNetworkType;
    }

    /**
     * 获取固件版本
     *
     * @return
     */
    public static String uniwinGetFirmwareVersion() {
        if (!TextUtils.isEmpty(OTA_VERSION)) return OTA_VERSION;
        OTA_VERSION = "----";
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class);
            OTA_VERSION = (String) get.invoke(c, "ro.product.firmware");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return OTA_VERSION;
    }

    /**
     * 获取 android 版本:
     *
     * @return
     */
    public String UniwinGetAndroidVersion() {
        return Build.VERSION.RELEASE;
    }

    /**
     * 获取设备型号:
     *
     * @return
     */
    public String UniwinGetDeviceModel() {
        return Build.MODEL;
    }

    /**
     * 获取内核版本
     */
    public static String UniwinGetKernelVersion() {
        String kernelVersion = "";
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream("/proc/version");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return kernelVersion;
        }
        BufferedReader bufferedReader = new BufferedReader(new
                InputStreamReader(inputStream), 8 * 1024);
        String info = "";
        String line = "";
        try {
            while ((line = bufferedReader.readLine()) != null) {
                info += line;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedReader.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            if (info != "") {
                final String keyword = "version ";
                int index = info.indexOf(keyword);
                line = info.substring(index + keyword.length());
                index = line.indexOf(" ");
                kernelVersion = line.substring(0, index);
            }
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
        }
        return kernelVersion;
    }

    //隐藏系统键盘
    public static void hideKeyBoard(EditText editText) {
        if (editText == null) return;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            editText.setShowSoftInputOnFocus(false);
        } else {
            editText.setInputType(InputType.TYPE_NULL);
        }
        editText.setLongClickable(false);
        editText.setTextIsSelectable(false);
        //禁用拼写检查
        editText.setInputType(editText.getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
    }
    //    public void hideSoftInput(final EditText editText){
//            Class<EditText> cls = EditText.class;
//            Method method;
//            try {
//                method = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
//                method.setAccessible(true);
//                method.invoke(editText, false);
//            } catch (Exception e) {
//            }
//
//            try {
//                method = cls.getMethod("setSoftInputShownOnFocus", boolean.class);
//                method.setAccessible(true);
//                method.invoke(editText, false);
//            } catch (Exception e) {
//            }
//    }

    /**
     * @return 获取所有有效的网卡
     */
    public static String[] getAllNetInterface() {
        ArrayList<String> availableInterface = new ArrayList<>();
        String[] interfaces = null;
        try {
            //获取本地设备的所有网络接口
            Enumeration nis = NetworkInterface.getNetworkInterfaces();
            InetAddress ia = null;
            while (nis.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) nis.nextElement();
                Enumeration<InetAddress> ias = ni.getInetAddresses();
                while (ias.hasMoreElements()) {
                    ia = ias.nextElement();
                    if (ia instanceof Inet6Address) {
                        continue;// skip ipv6
                    }
                    String ip = ia.getHostAddress();
                    // 过滤掉127段的ip地址
                    if (!"127.0.0.1".equals(ip)) {
                        if (ni.getName().substring(0, 3).equals("eth")) {//筛选出以太网
                            availableInterface.add(ni.getName());
                        }
                    }
                }
            }

        } catch (SocketException e) {
            e.printStackTrace();
        }
        int size = availableInterface.size();
        if (size > 0) {
            interfaces = new String[size];
            for (int i = 0; i < size; i++) {
                interfaces[i] = availableInterface.get(i);
            }
        }
        return interfaces;
    }

//    /**
//     * 获取指定网卡ip
//     *
//     * @param netInterface
//     * @return
//     * @throws SocketException
//     */
//    public static String getIpAddress(String netInterface){
//        String hostIp = "";
//        try {
//            Enumeration nis = NetworkInterface.getNetworkInterfaces();
//            InetAddress ia = null;
//            while (nis.hasMoreElements()) {
//                NetworkInterface ni = (NetworkInterface) nis.nextElement();
//                if (ni.getName().equals(netInterface)) {
//                    Enumeration<InetAddress> ias = ni.getInetAddresses();
//                    while (ias.hasMoreElements()) {
//                        ia = ias.nextElement();
//                        if (ia instanceof Inet6Address) {
//                            continue;// skip ipv6
//                        }
//                        String ip = ia.getHostAddress();
//                        // 过滤掉127段的ip地址
//                        if (!"127.0.0.1".equals(ip)) {
//                            hostIp = ia.getHostAddress();
//                            break;
//                        }
//                    }
//                }
//            }
//        } catch (SocketException e) {
//            e.printStackTrace();
//        }
//        return hostIp;
//    }
//
//    /**
//     * 根据adb shell命令获取
//     * DNS地址
//     * @param name 网卡名称
//     * @return
//     */
//    public static String getLocalDNS(String name) {
//        Process cmdProcess = null;
//        BufferedReader reader = null;
//        String dnsIP = "";
//        try {
//            cmdProcess = Runtime.getRuntime().exec("getprop net.dns1");
//            reader = new BufferedReader(new InputStreamReader(cmdProcess.getInputStream()));
//            dnsIP = reader.readLine();
//            return dnsIP;
//        } catch (IOException e) {
//            return null;
//        } finally {
//            try {
//                reader.close();
//            } catch (IOException e) {
//            }
//            cmdProcess.destroy();
//        }
//    }
//
//    /**
//     * 获取掩码
//     *
//     * @param name
//     * @return
//     */
//    public static String getLocalMask(String name) {
//        Process cmdProcess = null;
//        BufferedReader reader = null;
//        String dnsIP = "";
//        try {
//            cmdProcess = Runtime.getRuntime().exec("getprop net.mask");
//            reader = new BufferedReader(new InputStreamReader(cmdProcess.getInputStream()));
//            dnsIP = reader.readLine();
//            return dnsIP;
//        } catch (IOException e) {
//            return null;
//        } finally {
//            try {
//                reader.close();
//            } catch (IOException e) {
//            }
//            cmdProcess.destroy();
//        }
//    }
//
//    /**
//     * 获取网关地址
//     *
//     * @param name
//     * @return
//     */
//    public static String getLocalGATE(String name) {
//        Process cmdProcess = null;
//        BufferedReader reader = null;
//        String dnsIP = "";
//        try {
//            cmdProcess = Runtime.getRuntime().exec("getprop net.gateway");
//            reader = new BufferedReader(new InputStreamReader(cmdProcess.getInputStream()));
//            dnsIP = reader.readLine();
//            return dnsIP;
//        } catch (IOException e) {
//            return null;
//        } finally {
//            try {
//                reader.close();
//            } catch (IOException e) {
//            }
//            cmdProcess.destroy();
//        }
//    }


    /**
     * 设置dns2默认114.114.114.114
     *
     * @return
     */
    public static void setDns2As114() {
        Process exec;
        BufferedReader reader = null;
        String dns = "";
        try {
            exec = Runtime.getRuntime().exec("getprop net.dns2");
            reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
            dns = reader.readLine();
            if (!TextUtils.equals(dns, "114.114.114.114")) {
                Runtime.getRuntime().exec("setprop net.dns2 114.114.114.114");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断当前应用是否在栈顶
     *
     * @param context
     * @return
     */
    public static boolean isAppOnForground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Activity.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcessInfoList = activityManager.getRunningAppProcesses();
        if (appProcessInfoList == null) {
            return false;
        }

        String packageName = context.getPackageName();
        for (ActivityManager.RunningAppProcessInfo processInfo : appProcessInfoList) {
            if (processInfo.processName.equals(packageName)) {
                //KLog.e("isOnForground====="+processInfo.importance);
            }
            if (processInfo.processName.equals(packageName) && (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 执行shell 命令， 命令中不必再带 adb shell
     *
     * @param cmd
     * @return Sting  命令执行在控制台输出的结果
     */
    public static String execByRuntime(String cmd) {
        Process process = null;
        BufferedReader bufferedReader = null;
        InputStreamReader inputStreamReader = null;
        try {
            process = Runtime.getRuntime().exec(cmd);
            inputStreamReader = new InputStreamReader(process.getInputStream());
            bufferedReader = new BufferedReader(inputStreamReader);

            int read;
            char[] buffer = new char[4096];
            StringBuilder output = new StringBuilder();
            while ((read = bufferedReader.read(buffer)) > 0) {
                output.append(buffer, 0, read);
            }
            return output.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (null != inputStreamReader) {
                try {
                    inputStreamReader.close();
                } catch (Throwable t) {
                    //
                }
            }
            if (null != bufferedReader) {
                try {
                    bufferedReader.close();
                } catch (Throwable t) {
                    //
                }
            }
            if (null != process) {
                try {
                    process.destroy();
                } catch (Throwable t) {
                    //
                }
            }
        }
    }

    public static String getProp(String propName) {
        String propString = null;
        try {
            Class<?> classType = Class.forName("android.os.SystemProperties");
            Method getMethod = classType.getMethod("get", String.class);
            propString = (String) getMethod.invoke(classType, propName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return propString;
    }

    public static String getProperty(String propName) {
        String propString = null;
        try {
            Class<?> classType = Class.forName("android.os.SystemProperties");
            Method getMethod = classType.getMethod("get", String.class);
            propString = (String) getMethod.invoke(classType, propName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return propString;
    }

    public static void setProperty(String key, String value) {
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method set = c.getMethod("set", String.class, String.class);
            set.invoke(c, key, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * * 获取android总运行内存大小
     * * @param context
     * *
     */
    public static String getTotalMemory(Context context) {
        String str1 = "/proc/meminfo";// 系统内存信息文件
        String str2;
        String[] arrayOfString;
        long initial_memory = 0;
        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
            str2 = localBufferedReader.readLine();// 读取meminfo第一行，系统总内存大小
            arrayOfString = str2.split("\\s+");
            for (String num : arrayOfString) {
                Log.i(str2, num + "\t");
            }
            // 获得系统总内存，单位是KB
            int i = Integer.valueOf(arrayOfString[1]).intValue();
            //int值乘以1024转换为long类型
            initial_memory = new Long((long) i * 1024);
            localBufferedReader.close();
        } catch (IOException e) {
        }
        return Formatter.formatFileSize(context, initial_memory);// Byte转换为KB或者MB，内存大小规格化

    }

    /**
     * 修复硬盘
     * @param path
     */
    public static void repairDisk(String path) {
        File file = new File(path);
        if (file.exists()) {
            Process cmdProcess = null;
            BufferedReader reader = null;
            String dnsIP = "";
            try {
                cmdProcess = Runtime.getRuntime().exec("e2fsck -a " + path);
                reader = new BufferedReader(new InputStreamReader(cmdProcess.getInputStream()));
                dnsIP = reader.readLine();
            } catch (IOException e) {
            } finally {
                try {
                    reader.close();
                } catch (IOException e) {
                }
                cmdProcess.destroy();
            }
        }
    }

    /**
     * 获取硬盘类型
     *
     * @param context
     * @param path
     * @return
     */
    public static String getDiskHardType(Context context, String path) {
        String fsType = "";
        StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
        try {
            Class storeManagerClazz = Class.forName("android.os.storage.StorageManager");
            Method getVolumesMethod = storeManagerClazz.getMethod("getVolumes");
            List<?> volumeInfos = (List<?>) getVolumesMethod.invoke(storageManager);
            Class volumeInfoClazz = Class.forName("android.os.storage.VolumeInfo");
            Method getFsUuidMethod = volumeInfoClazz.getMethod("getFsUuid");

            Field fsTypeField = volumeInfoClazz.getDeclaredField("fsType");
            Field pathField = volumeInfoClazz.getDeclaredField("path");

            if (volumeInfos != null) {
                for (Object volumeInfo : volumeInfos) {
                    String uuid = (String) getFsUuidMethod.invoke(volumeInfo);
                    if (uuid != null) {
                        String pathString = (String) pathField.get(volumeInfo) + "/";
                        if (TextUtils.equals(path, pathString)) {
                            fsType = (String) fsTypeField.get(volumeInfo);
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fsType;
    }

    /**
     * 控制底部导航栏，显示/隐藏虚拟按键
     *
     * @param isShow true:显示；false：隐藏
     */
    public static void controlBottomNavigation(Activity activity, boolean isShow) {
        //隐藏虚拟按键
        if (isShow) {
            activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        } else {
            activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE);
        }
    }
}
